package com.sd.trans.controller;

import com.sd.trans.baidu.TransApi;
import com.sd.trans.entity.TransRec;
import com.sd.trans.service.TransRecService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/translate")
public class TranslateController {

    // 在平台申请的APP_ID 详见 https://fanyi-api.baidu.com/api/trans/product/desktop?req=developer
    @Value("${baidu.translate.app-id}")
    private String appId;
    
    @Value("${baidu.translate.security-key}")
    private String securityKey;

    @Resource
    private TransRecService transRecService;

    @PostMapping
    public Map<String, Object> translate(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String sourceText = request.get("sourceText");
            String targetLang = request.get("targetLang");

            // 首先检查数据库中是否有符合条件的翻译记录
            TransRec existingRecord = transRecService.queryByFromTextAndLang(sourceText, targetLang);
            String translatedText;
            
            if (existingRecord != null) {
                // 如果数据库中有记录，则直接使用数据库中的翻译结果
                translatedText = existingRecord.getToText();
            } else {
                // 否则调用百度翻译API
                TransApi api = new TransApi(appId, securityKey);
                String result = api.getTransResult(sourceText, "auto", targetLang);

                // 解析翻译结果
                translatedText = parseTranslationResult(result);

                // 保存翻译记录
                TransRec transRec = new TransRec();
                transRec.setFromText(sourceText);
                transRec.setLang(targetLang);
                transRec.setToText(translatedText);
                transRecService.insert(transRec);
            }

            response.put("success", true);
            response.put("translatedText", translatedText);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "翻译失败: " + e.getMessage());
        }
        return response;
    }

    private String parseTranslationResult(String result) {
        // 简单解析百度翻译API返回的结果
        // 格式类似: {"from":"zh","to":"en","trans_result":[{"src":"你好","dst":"Hello"}]}
        try {
            int dstIndex = result.indexOf("\"dst\":\"");
            if (dstIndex != -1) {
                int start = dstIndex + 7; // "dst":" 的长度是7
                int end = result.indexOf("\"", start);
                if (end != -1) {
                    // 处理转义字符
                    String translated = result.substring(start, end);
                    // 替换常见的转义字符
                    translated = translated.replace("\\\"", "\"");
                    translated = translated.replace("\\n", "\n");
                    translated = translated.replace("\\r", "\r");
                    // 处理Unicode编码字符
                    translated = decodeUnicode(translated);
                    return translated;
                }
            }
        } catch (Exception e) {
            // 解析失败则返回原始结果
            return result;
        }
        return result;
    }

    /**
     * 将字符串中的Unicode编码转换为中文字符
     * @param str 包含Unicode编码的字符串
     * @return 转换后的字符串
     */
    private String decodeUnicode(String str) {
        StringBuilder sb = new StringBuilder(str.length());
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '\\' && i < chars.length - 5 && chars[i + 1] == 'u') {
                try {
                    // 取出unicode编码，例如 \u4e2d
                    String unicode = String.valueOf(chars, i + 2, 4);
                    // 转换为十进制整数
                    int value = Integer.parseInt(unicode, 16);
                    // 转换为字符
                    sb.append((char) value);
                    // 跳过已处理的字符
                    i += 5;
                } catch (NumberFormatException e) {
                    // 如果转换失败，按原样添加
                    sb.append(chars[i]);
                }
            } else {
                sb.append(chars[i]);
            }
        }
        return sb.toString();
    }
}